<template>
  <div>
    <div>
      <el-button type="primary" @click="goToAdd">新增</el-button>
    </div>
    <el-table :data="books" style="width: 100%;">
      <el-table-column fixed label="序号" width="120">
        <template #default="{ $index }">
          <span>{{ $index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="false" prop="id" label="id" width="120"/>
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column prop="author" label="作者"></el-table-column>
      <el-table-column prop="price" label="价格"></el-table-column>
      <el-table-column prop="num" label="数量"></el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="{ row }">
          <el-button link type="primary" size="default" @click="goToEdit(row)">修改</el-button>
          <el-button link type="danger" size="default" @click="showConfirm(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <div style="display: flex; align-items: center; justify-content: space-between;">
      <el-button type="primary" v-if="currentPage > 1" @click="firstPage">首页</el-button>
      <el-button type="primary" @click="prevPage">上一页</el-button>
      <div style="margin: 0 10px;">当前页：{{ currentPage }} / {{ totalPage }}</div>
      <div style="margin: 0 10px;">总数量：{{ totalDatas }}</div>
      <div>
        <span>每页显示：</span>
        <el-input v-model.number="pageSize" @change="changePageSize" style="width: 50px;"></el-input>
      </div>
      <el-button type="primary" @click="nextPage">下一页</el-button>
      <el-button type="primary" v-if="currentPage < totalPage" @click="endPage">尾页</el-button>
    </div>
    <!-- 弹窗 -->
    <el-dialog v-model="editDialogVisible" :title="digTitle">
      <el-form :model="editForm">
        <el-form-item label="标题">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="editForm.author"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model.number="editForm.price"></el-input>
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model.number="editForm.num"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitData">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, watchEffect, reactive} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import axios from 'axios';
import qs from 'qs';
import {urlData} from "@/utils/url.js";

const books = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
let totalPage = ref(1);
let totalDatas = ref(0);

const editDialogVisible = ref(false);
const digTitle = ref('');
const editForm = reactive({
  id: '',
  title: '',
  author: '',
  price: 0,
  num: 0,
});

const fetchBooks = async () => {
  try {
    await axios.get(urlData("book/list"), {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
    }).then(res => {
          console.log('res.data===>', res.data);
          if (res.data.code === 200) {
            books.value = res.data.data.books;
            totalDatas.value = res.data.data.total;
            totalPage.value = Math.ceil(res.data.data.total / pageSize.value);
            if (currentPage.value > totalPage.value) {
              currentPage.value = totalPage.value;
            }
          } else {
            console.error('Error fetching books:', res.data.message);
          }
        },
        error => {
          console.error('Error fetching books:', error.code);
        }
    )
  } catch (error) {
    console.error('Error fetching books:', error);
  }
};

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    fetchBooks();
  } else {
    ElMessage.error('已经是第一页');
  }
};

const nextPage = () => {
  if (currentPage.value < totalPage.value) {
    currentPage.value++;
    fetchBooks();
  } else {
    ElMessage.error('已经是最后一页');
  }
};

const firstPage = () => {
  currentPage.value = 1;
  fetchBooks();
};

const endPage = () => {
  currentPage.value = totalPage.value;
  fetchBooks();
};

const changePageSize = () => {
  currentPage.value = 1;
  fetchBooks();
};

watchEffect(pageSize, () => {
  fetchBooks();
});

onMounted(() => {
  fetchBooks();
});

const showConfirm = (id) => {
  const row = books.value.find(item => item.id === id);
  console.log('row===>', row);
  ElMessageBox.confirm(`确认要删除【${row.title}】吗?`, '删除提醒', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteUser(id);
  }).catch(() => {
  });
};

const deleteUser = async (id) => {
  await axios.delete(urlData("book/delete"), {
    params: {
      id: id
    }
  }).then(res => {
    if (res.data.code === 200) {
      ElMessage.success('删除成功');
      fetchBooks();
    } else {
      ElMessage.error('删除失败');
    }
  }).catch(error => {
    console.error('Error deleting user:', error);
    ElMessage.error(error.code);
  });
};

const goToEdit = (row) => {
  digTitle.value = '编辑书籍信息';
  console.log('row===>', row);
  editForm.id = row.id;
  editForm.title = row.title;
  editForm.author = row.author;
  editForm.price = row.price;
  editForm.num = row.num;
  editDialogVisible.value = true;
};

const goToAdd = () => {
  digTitle.value = '新增书籍信息';
  editForm.id = '';
  editForm.title = '';
  editForm.author = '';
  editForm.price = 0;
  editForm.num = 0;
  editDialogVisible.value = true;
}

const submitData = async () => {
  console.log('editForm===>', editForm.id, editForm.title, editForm.author, editForm.price, editForm.num);
  //id为空, 为增加
  if (editForm.id === '') {
    console.log('totalPage===>', totalPage.value);
    console.log("id is empty")
    await axios.post(urlData("book/add"), qs.stringify({
      title: editForm.title,
      author: editForm.author,
      price: editForm.price,
      num: editForm.num
    })).then(res => {
      if (res.data.code === 200) {
        ElMessage.success('新增成功');
        editDialogVisible.value = false;
        endPage();
      } else {
        ElMessage.error(res.data.msg);
      }
    }).catch(error => {
      console.error('新增失败: ', error);
      ElMessage.error(error.code);
    });
    //id不为空, 为修改
  } else {
    console.log("id is not empty")
    await axios.put(urlData("book/update"), qs.stringify({
      id: editForm.id,
      title: editForm.title,
      author: editForm.author,
      price: editForm.price,
      num: editForm.num
    })).then(res => {
      if (res.data.code === 200) {
        ElMessage.success('修改成功');
        editDialogVisible.value = false;
        fetchBooks();
      } else {
        ElMessage.error(res.data.msg);
      }
    }).catch(error => {
      console.error('修改失败: ', error);
      ElMessage.error(error.code);
    });
  }
};


</script>

















